package com.liu.controller;


import com.liu.common.exception.FileNotExistException;
import com.liu.common.exception.FileSizeLimitException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@RestController
public class UploadController {

    private final String BASEDIR= "/attchment";//所有上传文件的根目录


    @Value("${spring.servlet.multipart.max-file-size}")
    long maxFileSize;



    @PostMapping("/upload")
    public String upload(MultipartFile file, HttpServletRequest request){

        return toUpload(file, request,null);
    }


    @PostMapping("/batch/upload")
    public List batchUpdate(List<MultipartFile> files, HttpServletRequest request){
        List<String> list = new ArrayList<>();
        //批量上传
        files.forEach(file -> {
            if (!file.isEmpty()){
                String tmp = toUpload(file, request,null);
                list.add(tmp);
            }
        });
        return list;
    }




    /**
     * 上传单个文件
     * @param file
     * @param request
     * @param type 目录如果为空 默认为image
     * @return
     */
    String toUpload(MultipartFile file, HttpServletRequest request,String type){
        //先判断有没有附件
        if ("".equals(file.getOriginalFilename())){
            throw new FileNotExistException("请选择上传文件");
        }
        //获取文件大小
        if (file.getSize()>maxFileSize){
            throw new FileSizeLimitException("文件大小超过"+((maxFileSize / (1024 * 1024)))+"M");
        }
        //获取服务器上传的根目录
        FilePath root = initDir(request,type);
        String newFile = getNewFileName(file);
        try {
            file.transferTo(new File(root +"\\"+ newFile));
        }catch (IOException e){
            throw new RuntimeException(e);
        }
        return root.getDir()+"/"+newFile;
    }


    /**
     * 初始附件存储目录
     * @param request
     * @return
     */
    FilePath initDir(HttpServletRequest request,String type){
        if (null == type ||  "".equals(type))
            type = "images";
        //获取系统时间
        String relPath = BASEDIR+"/"+type+"/"+getSystrmYMD();
        //获取服务器上传的根目录
        String root = request.getServletContext().getRealPath("/")+relPath;
        File dir = new File(root);
        if(!dir.exists()){
            dir.mkdirs();//创建目录
        }
        return new FilePath(dir.getAbsolutePath(),relPath);
    }


    class FilePath{
        String root;
        String dir;

        public FilePath(String root, String dir) {
            this.root = root;
            this.dir = dir;
        }

        public String getRoot() {
            return root;
        }

        public void setRoot(String root) {
            this.root = root;
        }

        public String getDir() {
            return dir;
        }

        public void setDir(String dir) {
            this.dir = dir;
        }
    }



    /**
     * 获取新的文件名
     * @param file
     * @return
     */
    String getNewFileName(MultipartFile  file){
        //获取v上传文件的名称
        String filename = file.getOriginalFilename();
        //获取文件的后缀
        String suffix = filename.substring(filename.lastIndexOf("."));
        //新的文件名
        String newFileName = System.currentTimeMillis() + suffix;
        return newFileName;
    }


    /**
     * 获取系统时间
     * @return
     */
    String getSystrmYMD(){
        LocalDate localDate = LocalDate.now();
        return localDate.format(DateTimeFormatter.ofPattern("yMMdd"));
    }


}
